#include "todolist.h"
#include <fstream>

using namespace std;

Todolist::Todolist(string name){
    this->name = name;
}

const string Todolist::getName() const{
    return this->name;
}

void Todolist::addTask(string task){
	this->todolist.push_front(task);
}

void Todolist::toString(){
    if(this->todolist.empty()) {
        cout << "There is no tasks in the todolist" << endl;
    }
    else {
        list<string>::iterator it;
        int i = 0;
        for(it = this->todolist.begin(); it != this->todolist.end(); it++){
            i++;
            cout << i << ". " <<  *it << endl;
        }
    }
}

void Todolist::deleteTask(int position) {
    if(position > this->todolist.size() || position < 1) {
        cout << "This task does not exists!" << endl;
    }
    else {
        list<string>::iterator it;
        it = this->todolist.begin();
        advance(it,position-1);
        cout << "You have successfully fulfilled the task \"" << *it << "\", Bravo!" << endl;
        this->todolist.erase(it);
    }
}
void Todolist::save(string filePath) {
    ofstream todoFile (filePath.c_str());
    if (todoFile.is_open()) {
        list<string>::iterator it;
        for(it = this->todolist.begin(); it != this->todolist.end(); it++){
            todoFile << *it << endl;
        }
        //cout << "Todolist saved in file : \"" << filePath << "\"" << endl;
        todoFile.close();
    }
    else {
        cout << "Enable to save the todoList" << endl;
    }
}
void Todolist::load(string filePath) {
    string task;
    ifstream todoFile (filePath.c_str());
    if (todoFile.is_open()) {
        while (todoFile.good()) {
            getline(todoFile,task);
            if (task != "") {
                this->todolist.push_back(task);
            }
        }
        todoFile.close();
    }
}

void Todolist::deleteAllTasks() {
    this->todolist.clear();
    cout << "All tasks have been removed" << endl;
}

bool Todolist::empty() {
    return this->todolist.empty();
}
